using System;
using System.Reflection;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Configuration;
using System.Collections;
using System.Threading;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using ACM.cmsarea08;
using ACM.cmsarea08.mainconfiguration;



namespace ACM.cmsarea08.Core {
	public class VersionHandler :  IHttpAsyncHandler { //IHttpAsyncHandler IHttpHandler
/*
<?xml version="1.0" encoding="UTF-8"?>
<JoackVersion>
	<Version>123</Version>
	<Assemblies>
			<Assembly>
				<name>123</name>
				<version>123</version>
			</Assembly>
	</Assemblies>

</JoackVersion>
*/		
		
       public bool IsReusable { get { return true; } }
       const string assemblyS = "<Assembly>"+
				"<name>{0}</name>"+
				"<version>{1}</version>"+
			"</Assembly>\n\r";
      public void ProcessRequest(System.Web.HttpContext contesto)
        {
			// non usato
        }
		
	  public IAsyncResult BeginProcessRequest(HttpContext ctx, AsyncCallback cb, object obj)
	  {
	    AsyncVersionState reqState = new AsyncVersionState(ctx, cb, obj);
	    AsyncVersionRequest ar = new AsyncVersionRequest(reqState);
	    ThreadStart ts = new ThreadStart(ar.ProcessRequest);
	    Thread t = new Thread(ts);
	    t.Start();
	    return reqState;
	  }
        
	  public void EndProcessRequest(IAsyncResult ar)
	  {
	    AsyncVersionState ars = ar as AsyncVersionState;
	    if (ars != null)
	    {
	     // Clean Up
	    }
	  }      
      
	}
	
	public class AsyncVersionState : IAsyncResult {
		
		internal HttpContext _ctx;
		internal AsyncCallback _cb;
		internal object _dati;
		private bool _iscompleted = false;
		private ManualResetEvent _callCompleteEvent = null;
		
		public AsyncVersionState(HttpContext ctx, AsyncCallback cb, object dati) {
			_ctx = ctx;
			_cb = cb;
			_dati = dati;
			
		}
		internal void CompleteRequest() {
			_iscompleted = true;
			lock(this) {
				if(_callCompleteEvent!=null) {
					_callCompleteEvent.Set();
				}
				 if (_cb != null)
				 	_cb(this);
			}
		}
		public object AsyncState {
			get { return _dati; }
		}
		public bool CompletedSynchronously {
			get { return false; }
		}
		public bool IsCompleted            {
			get { return _iscompleted; }
		}
		public WaitHandle AsyncWaitHandle {
			get {
				lock(this) {
					if(_callCompleteEvent == null) 
						_callCompleteEvent = new ManualResetEvent(false);
					return _callCompleteEvent;
				}
			}
		}



	}
	class AsyncVersionRequest
	{
	 const string assemblyS = "<Assembly>"+
				"<name>{0}</name>"+
				"<version>{1}</version>"+
			"</Assembly>\n\r";		
	  private AsyncVersionState _asyncRequestState;
	
	  public AsyncVersionRequest(AsyncVersionState ars)
	  {
	    _asyncRequestState = ars;
	  }
	    
	  public void ProcessRequest()
	  {
       	string testo = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\r";
        	//qui blocco get version:
        	testo+="<JoackVersion>\n\r<Version>"+"{0}"+"</Version>\n\r<Assemblies>\n\r";
        	System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(_asyncRequestState._ctx.Server.MapPath("/bin"));
        	if(!di.Exists) {
        		_asyncRequestState._ctx.Response.Write("NO FOLDER");
        		_asyncRequestState._ctx.Response.End();
        		return;
        	}
        	System.IO.FileInfo[] filez = di.GetFiles("*.dll");
        	int countV = 0;
        	System.Int32 versionim = 0;
        	System.Int32 versioniM = 0;
        	System.Int32 versionib = 0;
        	for(int i = 0 ; i < filez.Length; i ++) {
        		string versione = "0";
        		if(filez[i].Name.ToLower().StartsWith("icsharpcode.")) continue;
        		if(filez[i].Name.ToLower().StartsWith("interop.")) continue;
        		if(filez[i].Name.ToLower().StartsWith("moxiecode.")) continue;
        		if(filez[i].Name.ToLower().StartsWith("mysql.")) continue;
        		if(filez[i].Name.ToLower().StartsWith("openflashchart.")) continue;
        		if(filez[i].Name.ToLower().StartsWith("unrar.")) continue;
                
	        	Assembly myA=null;
        		try {
                    if (filez[i].Name.ToLower().IndexOf("resources") == -1)
                    {
                        myA = System.Reflection.Assembly.Load(filez[i].Name.Replace(filez[i].Extension, ""));
                        versioniM += myA.GetName().Version.Major;
                        versionim += myA.GetName().Version.Minor;
                        versionib += myA.GetName().Version.Build;
                        versione =
                            myA.GetName().Version.ToString();
                        countV++;
                    }
        		} catch (Exception ex) {
        			versione ="N/A"; //"Errore : " + ex.ToString() + "\n";
        		} finally {
        			myA=null;
        		}
	        	testo+= string.Format(assemblyS,filez[i].Name,versione);
        	}
        	testo+="</Assemblies>\n\r</JoackVersion>\n\r";
        	
        	string latV =(versioniM/countV) +"." +
        			      (versionim/countV) +"." +
        				  (versionib/countV);
			_asyncRequestState._ctx.Response.ContentType = "text/xml";
			_asyncRequestState._ctx.Response.Write(string.Format(testo,latV.ToString()));

		//finito.
			
	    _asyncRequestState.CompleteRequest();
	  }
	}
	
}
